﻿
using System.Text;

using Demo.GIS.GadgetServices.ApiModels;
using Demo.GIS.GadgetServices.DBModels;

namespace Demo.GIS.GadgetServices
{
    public class GadgetServerManager
    {

        public static bool SaveGadgetInfo(SaveGadgetInfoRequest request)
        {
            var res = false;
            var insertSql = new StringBuilder();
            var gadgetInfoList = new List<DemoGadgetInfo>();
            request.Items.ForEach(item =>
            {
                var temp = new DemoGadgetInfo()
                {
                    Name = item.Name,
                    GadgetInfo = item.GadgetInfo,
                };
                _ = insertSql.Append(
                    $"INSERT INTO DemoSearchInfo(DSIID,DGIID,Info) VALUES ({LuanNiao.Core.IDGen.GetInstance().NextId()}" +
                    $",{temp.DGIID}" +
                    $", ST_GeomFromText('POINT({item.PointX} {item.PointY})'));");
                gadgetInfoList.Add(temp);
            });

            GCCEntrance.DBManager!.LocalDB!.Transaction(() =>
            {
                var dbInsertRes = GCCEntrance.DBManager.LocalDB.Insert(gadgetInfoList).ExecuteAffrows();
                if (dbInsertRes != gadgetInfoList.Count)
                {
                    throw new Exception("Save gadget info error.");
                }

                _ = GCCEntrance.DBManager.LocalDB.Ado.ExecuteNonQuery(insertSql.ToString());

                res = true;
            });


            return res;
        }

        public static SearchGadgetInfoResponse SearchGadgetInfo(string topLeft,
            string topRight,
           string bottomRight,
            string bottomLeft)
        {
            var res = new SearchGadgetInfoResponse();
            var searchKey = $"POLYGON(({topLeft},{topRight},{bottomRight},{bottomLeft},{topLeft}))";
            var dbRESList = GCCEntrance.DBManager!.LocalReadDB!.Select<DemoSearchInfo>()
                .Include(item => item.GadgetInfo)
                .As("a")
                .Where(" ST_Intersects( a.info, ST_GeomFromText(?bbox) ) ", new
                {
                    bbox = searchKey,
                })
                .ToList();
            dbRESList.ForEach(item => res.Items.Add(new SearchGadgetInfoResponse.SearchGadgetInfoResponseItem()
            {
                GadgetInfo = item.GadgetInfo.GadgetInfo,
                Name = item.GadgetInfo.Name

            }));
            return res;
        }
    }
}
